# -*- coding: utf-8 -*-
"""
@Time ： 2021/4/19 0:37
@Auth ： Mr. royalday 2487625775
@Company ： 2487625775@qq.cpm
@Function ：用户相关功能：注册、短信、登录、注销
"""
import uuid
from datetime import datetime
from io import BytesIO

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django_redis import get_redis_connection

from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm, UpdatePasswordForm, \
    PersonalCenterModelForm
from django.http import JsonResponse
from django.core.exceptions import ValidationError


def redirect_index(request):
    return render(request, 'index.html')


def register(request):
    """
    注册
    :param request:
    :return:
    """
    # print(request.POST)
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, "register.html", {'form': form})
    if request.method == 'POST':
        form = RegisterModelForm(data=request.POST)
        if form.is_valid():
            try:
                # 验证通过之后，写入数据库（注意：密码需要做个密文处理）
                instance = form.save()  # form.save() 会自动提交form表单中的数据到数据库，并且会自动剔除没用的字段
            except Exception:
                raise ValidationError("注册失败！！！")
                print(Exception.__traceback__())
            try:
                # 创建交易记录
                policy_object = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
                models.Transaction.objects.create(
                    status=2,
                    order=str(uuid.uuid4()),  # 生成随机字符串
                    user=instance,
                    price_policy=policy_object,
                    count=0,
                    price=0,
                    start_datetime=datetime.now()
                )
            except:
                raise ValidationError("创建交易记录失败！！！")
                print(Exception.__traceback__())

            return JsonResponse({'status': True, 'data': '/login/'})

    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """
    发送短信
    :param request:
    :return:
    """
    print(request.GET.get('mobile_phone'))
    form = SendSmsForm(request, data=request.GET)
    # 校验手机号码：不能为空、格式是否正确
    # form.clean_mobile_phone()
    if form.is_valid():
        # 写短信
        # 写redis
        return JsonResponse({'status': True})
    print(request.GET.get('mobile_phone'))
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """
    短信登录
    :param request:
    :return:
    """
    if request.tracer.user:
        return redirect("web:index")

    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})
    form = LoginSmsForm(data=request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功
        user_object = form.cleaned_data['mobile_phone']
        # 用户信息放入session
        request.session['user_id'] = user_object.id
        # request.session['username'] = user_obj.username
        request.session.set_expiry(60 * 60 * 24 * 14)  # 登录成功后重新设置session过期时间

        print(user_object.username, user_object.email)

        # 通过手机号移除redis中对应手机号保存的验证码
        conn = get_redis_connection()
        conn.delete(user_object.mobile_phone)

        return JsonResponse({'status': True, 'data': '/index/'})
    print(request.GET.get('mobile_phone'))
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """
    用户名密码登录
    :param request:
    :return:
    """

    if request.method == 'GET':
        # print(request.GET.items())
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})

    form = LoginForm(request, data=request.POST)

    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        # user_object_by_mob = models.UserInfo.objects.filter(username=username, password=password).first()
        # 实现邮箱或者手机号码作为用户名登录
        from django.db.models import Q
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()

        if user_object:
            # 用户名密码正确
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)  # 登录成功后重新设置session过期时间
            return redirect('web:index')
        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


def img_code(request):
    """
    获取图片验证码
    :param request:
    :return:
    """
    from utils.img_code import check_code
    img_object, code = check_code()

    # 将图片验证码保存到session中
    request.session['img_code'] = code
    request.session.set_expiry(60)  # 设置当前session的过期时间为60s

    # 保存验证码图片到内存：不放在本地，防止多用户冲突
    stream = BytesIO()
    img_object.save(stream, 'png')
    print(code)
    return HttpResponse(stream.getvalue())


def logout(request):
    """
    退出登录
    :param request:
    :return:
    """
    request.session.flush()  # 清理session信息
    return redirect('web:index')


def update_password(request):
    if request.method == 'GET':
        form = UpdatePasswordForm(request)
        return render(request, 'update_password.html', {'form': form})
    form = UpdatePasswordForm(request, data=request.POST)

    if form.is_valid():
        password = form.cleaned_data['new_password']
        user_id = request.tracer.id
        models.UserInfo.objects.filter(id=user_id).update(password=password)
        return logout(request)
    return render(request, 'update_password.html', {'form': form})


def personal_center(request):
    form = PersonalCenterModelForm(instance=request.tracer.user)

    return render(request, 'personal_center.html', {'form': form})
